package org.example.springtest.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.springtest.model.dto.user.LoginResponse;
import org.example.springtest.model.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements org.example.springtest.service.RedisService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private final ObjectMapper objectMapper = new ObjectMapper();
    private static final String USER_HASH_KEY = "userList";

    /**
     * Hash添加用户
     */
    public void addHashUser(User user) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(user);
            redisTemplate.opsForHash().put(USER_HASH_KEY, user.getId().toString(), json);
        } catch (Exception e) {
            throw new RuntimeException("序列化失败", e.getCause());
        }
    }

    public User getHashUser(Long userId) {
        try {
            Object value = redisTemplate.opsForHash().get(USER_HASH_KEY, userId.toString());
            if (value != null) {
                return new ObjectMapper().readValue(value.toString(), User.class);
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException("Redis Hash 读取失败: " + e.getMessage(), e);
        }
    }

    public void addUser(LoginResponse loginResponse, long time) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(loginResponse);
            String userKey = "user:" + loginResponse.getId();
            redisTemplate.opsForValue().set(userKey, json, time, TimeUnit.HOURS);
        } catch (Exception e) {
            throw new RuntimeException("Redis String 操作失败: " + e.getMessage(), e);
        }
    }

    public void set(String key, String value, long timeoutSeconds) {
        redisTemplate.opsForValue().set(key, value, Duration.ofSeconds(timeoutSeconds));
    }

    public Map get(String key) {
        try {
            String json =  redisTemplate.opsForValue().get(key);
            return objectMapper.readValue( (String) json, Map.class);
        } catch (Exception e) {
            throw new RuntimeException("Redis 读取失败: " + e.getMessage(), e);
        }
//        return redisTemplate.opsForValue().get(key);
    }

    public boolean delete(String key) {
        return Boolean.TRUE.equals(redisTemplate.delete(key));
    }


}
